#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/08/31 10:52
# @Author  : elegantfrog
# @FileName: inputData.py

from config import config
import paho.mqtt.client as mqtt
import time
import json
from utils import aUtils
import os
import datetime


class inputData():
    def __init__(self):
        self.HOST = config['mqtt']['host']
        self.PORT = config['mqtt']['port']
        self.USER = config['mqtt']['username']
        self.PWD = config['mqtt']['password']
        self.KEEPLIVE = 60
        self.client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        self.client = None
        self.pub_topic = ''
        self.sub_topic = 'seedlight/sub/'
        self.utils = aUtils()
        self.path = '../files/config.json'
        self.plan = []
        self.fileJosn = {}

    def client_start(self):
        self.pub_topic = 'seedlight/pub/'
        try:
            with open(self.path, 'r') as f:
                self.fileJson = json.load(f)
            self.plan = self.fileJson['workVal']['plan']
            res = self.utils.getDevCode(self.fileJson['files']['code'], 'r')
            print('SN: ' + res)
            self.sub_topic += res
            self.pub_topic += res
            self.client = mqtt.Client(self.client_id)  # ClientId不能重复，所以使用当前时间
            self.client.username_pw_set(self.USER, self.PWD)  # 必须设置，否则会返回「Connected with result code 4」
            self.client.on_connect = self.on_connect
            self.client.connect(self.HOST, self.PORT, self.KEEPLIVE)
            self.client.loop_start()
        except Exception as e:
            print(e)

    def on_connect(self, client, userdata, flags, rc):
        try:
            if rc == 0:
                print('mqtt server connection succeeded')
            else:
                print("Connected with result code " + str(rc))
                print('mqtt server connection failed')
        except Exception as e:
            print(e)

    def on_publish(self, data):
        try:
            self.client.publish(self.pub_topic, json.dumps(data))
        except Exception as e:
            print(e)

    def timePlan(self):
        curDate = time.strftime("%Y-%m-%d") + ' 00:00:00'
        startT = int(time.mktime(time.strptime(curDate, "%Y-%m-%d %H:%M:%S"))) - 8 * 3600
        current = int(time.time())
        for i in self.plan:
            if startT + i['s'] <= current and startT + i['s'] + i['e'] >= current:
                return {'status': True, 'ft': i['ft']}
            else:
                return {'status': False, 'ft': i['ft']}

    def getData(self):
        try:
            result = self.utils.getDevParams(self.fileJson['files'])
            return result
        except Exception as e:
            print(e)
            return None


if __name__ == '__main__':
    input = inputData()
    input.client_start()
    while True:
        res = input.timePlan()
        try:
            if res['status']:
                resObj = input.getData()
                payload = {
                    'method': 'u0',
                    'params': resObj['data']
                }
                input.on_publish(payload)
            time.sleep(res['ft'])
        except KeyboardInterrupt:
            print('exit')
            break
